package com.cychat.mall.controller;

import com.Cychat.commons.entity.ResultMessage;
import com.Cychat.commons.entity.pojo.*;
import com.cychat.mall.entity.DTO.ShoppingCartDTO;
import com.cychat.mall.params.OneProductOrderParams;
import com.cychat.mall.params.OrdersParams;
import com.cychat.mall.service.*;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-6:下午 7:12  <br/>
 * Description: 订单控制器
 */
@RestController
@RequestMapping("/api/mall")
@CrossOrigin
public class OrdersController {
    @Autowired
    OrdersService orderService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserService userService;
    @Autowired
    MerchantService merchantService;

    //通过用户id查询订单
    @GetMapping("/order/listByUserId/{userId}")
    public ResultMessage<List<Orders>> listByUserId(@PathVariable("userId") Long userId) {
        try {
            //根据用户id查询订单
            List<Orders> orders = orderService.listByUserId(userId);
            return ResultMessage.success(orders);
        } catch (Exception e) {
            return ResultMessage.error("查询订单失败");
        }
    }

    //根据用户ID和cartIds创建订单
    @PostMapping("/order/create/{userId}")
    public ResultMessage<List<String>> createOrder(
            @PathVariable("userId") Long userId,
            @Valid @RequestBody OrdersParams params) {
        return ResultMessage.success(orderService.createOrder(userId, params));
    }

//    根据用户ID和订单ID结算订单
    @PostMapping("/order/settlement/{userId}")
    public ResultMessage<String> settlementOrder(
            @PathVariable("userId") Long userId,
            @RequestParam("orderId") String orderId) {
        try {
            //根据用户id和订单id查询订单
            Orders order = orderService.getById(orderId);
            if (order == null) {
                return ResultMessage.error("订单不存在");
            }
            //判断订单是否属于该用户
            if (!order.getUserId().equals(userId)) {
                return ResultMessage.error("订单不属于该用户");
            }
            //判断订单状态是否为待付款
            if (!order.getOrderStatus().equals(0)) {
                return ResultMessage.error("订单状态错误");
            }
            //判断订单是否有商品
            if (order.getTotalAmount().equals(BigDecimal.ZERO)) {
                return ResultMessage.error("订单无商品");
            }
            //根据userId查询用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return ResultMessage.error("用户不存在");
            }
            //判断用户是否有足够的积分
            if (user.getPoints() < order.getTotalAmount().doubleValue()) {
                return ResultMessage.error("用户积分不足");
            }

            //更新用户积分
            user.setPoints(user.getPoints() - order.getTotalAmount().intValue());
            userService.updateById(user);
            //更新订单状态为已付款
            order.setOrderStatus(1);
            orderService.updateById(order);
            //给商家增加积分
            Merchant merchant = merchantService.getById(order.getMerchantId());
            if (merchant == null) {
                return ResultMessage.error("商家不存在");
            }
            merchant.setPoints(merchant.getPoints() + order.getTotalAmount().intValue());
            merchantService.updateById(merchant);

        } catch (Exception e) {
            return ResultMessage.error("订单结算失败");
        }
        return ResultMessage.success("订单结算成功");
    }

    //根据用户ID和订单ID确认收货
    @PostMapping("/order/confirm/{userId}")
    public ResultMessage<String> confirmOrder(
            @PathVariable("userId") Long userId,
            @RequestParam("orderId") String orderId) {
        try {
            //根据用户id和订单id查询订单
            Orders order = orderService.getById(orderId);
            if (order == null) {
                return ResultMessage.error("订单不存在");
            }
            //判断订单是否属于该用户
            if (!order.getUserId().equals(userId)) {
                return ResultMessage.error("订单不属于该用户");
            }
            //判断订单状态是否为已付款
            if (!order.getOrderStatus().equals(1)) {
                return ResultMessage.error("订单状态错误");
            }
            //更新订单状态为已确认收货
            order.setOrderStatus(2);
            orderService.updateById(order);
        } catch (Exception e) {
            return ResultMessage.error("订单确认收货失败");
        }
        return ResultMessage.success("订单确认收货成功");
    }

    //根据用户ID和商品ID生成订单
    @PostMapping("/order/createByProductId/{userId}")
    public ResultMessage<List<String>> createOrderByProductId(
            @PathVariable("userId") Long userId,
            @Valid @RequestBody OneProductOrderParams params) {
        try {
            //根据用户id和商品id创建订单
            List<String> orderIds = orderService.createOrderByProductId(userId, params);
            return ResultMessage.success(orderIds);
        } catch (Exception e) {
            return ResultMessage.error("订单创建失败");
        }
    }
}